﻿package com.htmlparser;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class Util {
	//判断字符串是否为0-9的数字
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (str == null) {
			return false;
		}
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}
	
	//读取磁盘文件，返回文件的字符串内容
	public static String ReadFile(String path) {
		File file = new File(path);
		StringBuffer sb = null;
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String temp = null;
			sb = new StringBuffer();
			temp = br.readLine();
			while (temp != null) {
				sb.append(temp + "\n");
				temp = br.readLine();
			}

		} catch (Exception e) {
			return "File not found";
		}
		if (sb != null) {
			return sb.toString();
		} else {
			return "File not found";
		}

	}

	// 判断js有没有返回值-----暂时没用到
	public static boolean hasReturn(String code) {
		int begin = code.indexOf("return");
		if (begin == -1) {
			return false;
		} else {
			int end = code.indexOf(";", begin);
			String returnContent = code.substring(begin + 6, end).trim();
			// System.out.println("return Content : 【"+returnContent+"】");
			if ((returnContent.equals("")) && (returnContent == null)) {
				return false;
			} else {
				return true;
			}
		}
	}

	
	//取得JavaScript的function的函数主体，即{}之间的代码
	public static String getMethodContent(String code, String method) {
		// 取method方法的方法体content
		String content = "";

		int begin = code.indexOf("function " + method);
		int b1 = code.indexOf("{", begin) + 1;
		int nextFunctionIndex = code.indexOf("function", b1);
		System.out.println("nextFunctionIndex=" + nextFunctionIndex);
		if (nextFunctionIndex != -1) {
			String temp = code.substring(b1, nextFunctionIndex).trim();
			int b2 = temp.lastIndexOf("}");
			content = temp.substring(0, b2).trim();

			// System.out.println("【method name : "+method+"()】");
			// System.out.println("====== code begin
			// ======\n\n"+code+"\n\n====== code end ======");

			// System.out.println("b1: "+b1);
			// System.out.println("b2: "+b2);

		} else {
			int b2 = code.lastIndexOf("}");
			
			System.out.println("");
			System.out.println("========== JavaScipt content begain===========");
			System.out.println("b1: "+b1);
			System.out.println("b2: "+b2);
			System.out.println("========== JavaScipt content end ===========");
			System.out.println("");
			
			if (b2 > b1) {
				
			}
			content = code.substring(b1, b2).trim();

			// System.out.println("【method name : "+method+"()】");
			// System.out.println("====== code begin
			// ======\n\n"+code+"\n\n====== code end ======");

			// System.out.println("b1: "+b1);
			// System.out.println("b2: "+b2);
		}
		return content;
	}

	//把Element对象转换成字符串，传给手机端
	public static String doc2String(Element data) {

		Format format = Format.getCompactFormat();
		format.setEncoding("GBK");// 设置xml文件的字符为gb2312，解决中文问题
		XMLOutputter xmlout = new XMLOutputter(format);
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		try {
			xmlout.output(data, bo);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String xmlStr = bo.toString();

		return xmlStr;
	}

	//取得超链接<a>里href的JavaScript函数的参数
	public static String[] getHrefParameters(String href) {
		String jsMethod = getHrefMethod(href);
		// 取方法的参数列表
		int begin = href.indexOf(jsMethod) + jsMethod.length() + 1;
		int end = href.indexOf(")", begin);
		String sArgs = href.substring(begin, end);
		String[] args = sArgs.split(",");

		// 去掉参数前后可能有的空格和引号
		for (int j = 0; j < args.length; j++) {
			args[j] = args[j].trim().replace("'", "");
			// System.out.println("getHrefParameters >>>>>>>
			// args["+j+"]=="+args[j]+"==");
		}
		return args;
	}
	
	//获取button的JavaScript函数的参数
	public static String[] getHrefParameters(String href, String jsMethod) {
		// 取方法的参数列表
		int begin = href.indexOf(jsMethod) + jsMethod.length() + 1;
		int end = href.indexOf(")", begin);
		String sArgs = href.substring(begin, end);
		String[] args = sArgs.split(",");

		// 去掉参数前后可能有的空格和引号
		for (int j = 0; j < args.length; j++) {
			args[j] = args[j].trim().replace("'", "");
			// System.out.println("getHrefParameters2 >>>>>>>
			// args["+j+"]=="+args[j]+"==");
		}
		return args;
	}

	
	//getScript，获得JavaScript的函数里面的形参列表
	public static String[] getJSParameters(String code, String jsMethod) {
		// 取方法的参数列表
		int index_method = code.indexOf("function " + jsMethod);
		int begin = code.indexOf("(", index_method);
		int end = code.indexOf(")", index_method);

//		System.out.println("");
//		System.out.println("【getJSParameters】code【" + code + "】");
//		System.out.println("【getJSParameters】jsMethod【" + jsMethod + "】");
//		System.out.println("【getJSParameters】index_method==" + index_method
//				+ "==");
//		System.out.println("【getJSParameters】begin==" + begin + "==");
//		System.out.println("【getJSParameters】end==" + end + "==");

		String sArgs = code.substring(begin + 1, end);
		System.out.println("");
		System.out.println("【getJSParameters】<script> 函数【" + jsMethod
				+ "】的所有参数 ==" + sArgs + "==");
		System.out.println("");
		String[] args = sArgs.split(",");

		// 去掉参数前后可能有的空格和引号
		for (int j = 0; j < args.length; j++) {
			args[j] = args[j].trim().replace("'", "");
			// System.out.println("getHrefParameters2 >>>>>>>
			// args["+j+"]=="+args[j]+"==");
		}
		return args;
	}

	
	//获取超链接<a>的href里面JavaScript函数的函数名
	public static String getHrefMethod(String href) {
		String temp = href.split(":")[1].replace(";", "");

		// 取方法名，不要后面的括号
		int i = temp.indexOf("(");
		String jsMethod = temp.substring(0, i);

		return jsMethod;
	}

	
	//把超链接<a>,button里面的JavaScript函数的数字型(本身是String类型)参数转换成float型
	public static float parameters_String2Float(String parameter) {
		float fParameter = 0;
		try {
			if ((parameter != null) && !(parameter.equals(""))) {
				fParameter = Float.parseFloat(parameter);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fParameter;
	}
	
	//过滤掉html字符串里的不需要解析或者解析不了的标签，考虑了大小写的问题
	//TODO html字符串过滤
	public static String filterString(String value) {
		//value = value.toLowerCase();
		value = value.replaceAll("<o:p>", "").replaceAll("</o:p>", "");
		value = value.replaceAll("<O:P>", "").replaceAll("</O:P>", "");
		
		value = value.replaceAll("<br>", "").replaceAll("<BR>", "");
		
		value = value.replaceAll("<b>", "").replaceAll("<B>", "");
		value = value.replaceAll("</b>", "").replaceAll("</B>", "");
		
		value = value.replaceAll("<p>", "").replaceAll("<P>", "");
		value = value.replaceAll("</p>", "").replaceAll("</P>", "");
		
		value = value.replaceAll("<u>", "").replaceAll("<U>", "");
		value = value.replaceAll("</u>", "").replaceAll("</U>", "");
		
		value = value.replaceAll("<span>", "").replaceAll("<SPAN>", "");
		value = value.replaceAll("</span>", "").replaceAll("</SPAN>", "");
		
		value = value.replaceAll("<font>", "").replaceAll("<FONT>", "");
		value = value.replaceAll("</font>", "").replaceAll("</FONT>", "");
		
		value = value.replaceAll("&nbsp;", "").replaceAll("&NBSP;", "");
		value = value.replaceAll("&nbsp", "").replaceAll("&NBSP", "");
	
		value = value.replaceAll("<strong>", "").replaceAll("<STRONG>", "");
		value = value.replaceAll("</strong>", "").replaceAll("</STRONG>", "");
		
		value = value.replaceAll(";", "");
		
		String[] html_lines = value.split("\n");
		StringBuffer html_buffer = new StringBuffer();
		
		System.out.println("html_lines.length=" + html_lines.length);
		for (int i=0;i<html_lines.length;i++) {
			//System.out.println("【"+i+"】");
			//一行里面可能有多个需要过滤的同一个标签
			String html_line = html_lines[i].trim();
			
			boolean hasP = ((html_line.indexOf("<p")>-1)|| (html_line.indexOf("<P")>-1));
			boolean hasSpan = ((html_line.indexOf("<span")>-1)|| (html_line.indexOf("<SPAN")>-1));
			boolean hasFont = ((html_line.indexOf("<font")>-1)|| (html_line.indexOf("<FONT")>-1));
			boolean hasB = (((html_line.indexOf("<b")>-1) &&(html_line.indexOf("<body")==-1))|| ((html_line.indexOf("<B")>-1) &&(html_line.indexOf("<BODY")==-1)));
			boolean hasXml = (html_line.indexOf("<?xml:namespace prefix")>-1);
			
			//处理上一行的残留标签
			//可能出现的问题：残留的标签是不需要过滤的标签，如table标签，属性太长，写成两行了，如果把它去掉，就很可能出错
//			int x1 = html_line.indexOf(">");
//			int x2 = html_line.indexOf("<");
//			
//			if (x1 >-1) {
//				if (x2>-1) {
//					if (x1<x2) {
//						html_line = html_line.substring(x1+1, html_line.length());
//					}
//				}else {
//					html_line = html_line.substring(x1+1, html_line.length());
//				}
//			}
			
			
			int w = 0;
			
			//while出现死循环，？？？
			//while (hasFont || hasB || hasP || hasSpan || hasXml) {
			
			//权宜之计，让每行都过滤5遍，防止一行当中有多个相同的标签需要过滤
			for(int j=0;j<5;j++){
				w++;
				//TODO 过滤 -- 可能出现的问题，"<span ..." 和 ">" 可能不在同一行
				if (html_line.indexOf("<span") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<span");
					int b1 = html_line.indexOf("<span");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("<SPAN") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<SPAN");
					int b1 = html_line.indexOf("<SPAN");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("<u") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<span");
					int b1 = html_line.indexOf("<u");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("<U") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<SPAN");
					int b1 = html_line.indexOf("<U");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				
				if (html_line.indexOf("<?xml:namespace prefix") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<?xml:namespace prefix");
					int b1 = html_line.indexOf("<?xml:namespace prefix");
					int b2 = html_line.indexOf(">", b1);
					
					//如果<?xml:namespace prefi没有在本行结束
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				
				if (html_line.indexOf("<p") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<p");
					int b1 = html_line.indexOf("<p");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("<P") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<P");
					int b1 = html_line.indexOf("<P");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("<font") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<font");
					int b1 = html_line.indexOf("<font");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("<FONT") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<FONT");
					int b1 = html_line.indexOf("<FONT");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if ((html_line.indexOf("<b") > -1) && (html_line.indexOf("<body") == -1)) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<b");
					int b1 = html_line.indexOf("<b");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("<B") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<B");
					int b1 = html_line.indexOf("<B");
					int b2 = html_line.indexOf(">", b1);
					if ((b2<0) || (b1>b2)) {
						html_line = html_line.substring(0, b1);
					} else {
						html_line = html_line.substring(0, b1) + html_line.substring(b2+1, html_line.length());
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				
				if (html_line.indexOf("alert") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<alert");
					//有时候会把"{"和"alert"写在一行里
					if (html_line.indexOf("{")>-1) {
						html_line = "{";
					} else {
						html_line = " ";
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				if (html_line.indexOf("ALERT") > -1) {
					//System.out.println("【"+i+"】"+html_line);
					//System.out.println("包含<ALERT");
					//有时候会把"{"和"alert"写在一行里
					if (html_line.indexOf("{")>-1) {
						html_line = "{";
					} else {
						html_line = " ";
					}
					//System.out.println("【"+i+"】=="+html_line+"==");
					//System.out.println("");
				}
				//System.out.println("【"+w+"】while_loop");
			}//while_loop_end 
			html_line = html_line.trim();
			html_buffer.append(html_line + "\n");
			
		}//for_loop_end
		value = html_buffer.toString();
		System.out.println("over!!!!!!!");
		return value;
	}
	
	public static String getDate(){
		String date = "";
		SimpleDateFormat sm=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		date = sm.format(new Date());
		
		return date;
	}
	
	//显示value的前一个关键字，如：document.form1.SAVE_FLAG.value，返回SAVE_FLAG
	public static String getHiddenName(String string){
		String result = "";
		string.replaceAll(".value", "");
		String[] temp = string.split("\\u002E");//转义点"."
		result = temp[temp.length-1];
		
		return result;
	}
	
	//提取JavaScript的内部的代码
	public static String getScriptCode(String html){
		String script = "";
		int b1 = html.indexOf("<script");
		if (b1 == -1) {
			b1 = html.indexOf("<SCRIPT");
		}
		int b2 = html.indexOf(">", b1);
		int b3 = html.indexOf("</script>", b2);
		if (b1 == -1) {
			b3 = html.indexOf("</SCRIPT>", b2);
		}
		
		script = html.substring(b2+1, b3);
		
		return script;
	}
	
	public static String doJSHidden(String html, Hashtable hiddens ){
		StringBuffer html_buffer = new StringBuffer();
		String[] htmls = html.split("\n");
		for (String string : htmls) {
			//System.out.println("WWWWWWWWWWWWWWWWWWWWWWWW b WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");
			System.out.println(string.trim());
			String temp  = string.trim();
			if (temp.indexOf("=") > -1) {
				if ((temp.indexOf("document") > -1) && (temp.indexOf("value") > -1)) {
					String[] s = temp.split("=");
					//if ((s[0].indexOf("document") > -1) && (s[0].indexOf("value") > -1)) {
					if(s[0].indexOf("document") > -1) {
						if (s[0].indexOf("value") > -1) {
							s[0] = Util.getHiddenName(s[0]);
						}
						if ((s[1].indexOf("document") > -1) && (s[1].indexOf("value") > -1)) {
							s[1] = Util.getHiddenName(s[1]);
							if (s[1] != null) {
								s[1] = (String)hiddens.get(s[1]);
							}
						}
					}else{
						if ((s[1].indexOf("document") > -1) && (s[1].indexOf("value") > -1)) {
							s[1] = Util.getHiddenName(s[1]);
							if (s[1] != null) {
								s[1] = (String)hiddens.get(s[1]);
							}
						}
					}
					
					temp = s[0] + " = " + s[1];
				}
			}
			html_buffer.append(temp + "\n");
			//System.out.println("WWWWWWWWWWWWWWWWWWWWWWWWW e WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW");
		}
		html = html_buffer.toString();
		return html;
	}
}
